package com.server.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ObjectUtils.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.stereotype.Service;

import com.server.date.DateType;
import com.server.date.DateUtil;
import com.server.service.ICourseManageService;
import com.server.service.ICourseStudyService;
import com.server.service.IUserAssignmentService;
import com.server.web.DataVector;
import com.server.web.RequestInput;
import com.sun.org.apache.xml.internal.serialize.IndentPrinter;
import com.sun.xml.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;

/**
 * @author wufeng
 * @date 创建时间：2016年7月13日 下午4:56:38 
 */
@Service("CourseManageService")
public class CourseManageService implements ICourseManageService{
	private static String tableName = "education.course";
	@Autowired
	private JdbcTemplate jdbctemplate;
	@Autowired
	private CommonDataService commonDataService;
	@Autowired
	private IUserAssignmentService userAssignmentService;
	@Autowired
	private ICourseStudyService courseStudyService;
	
	@Override
	public Map<String, Object> getCourseInfo(String id) {
		String sql = "select * from %s where id = '%s' and valid = 1 ORDER BY orderTime DESC";
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try {
			list = jdbctemplate.queryForList(String.format(sql, "education.v_course_class",id));
			Map<String, Object> relMap = new HashMap<String, Object>();
			relMap = courseStudyService.getVidoPptRelation(Integer.parseInt(id));
			list.get(0).putAll(relMap);
		} catch (Exception e) {
			list.get(0).put("error", "error");
		}
		return list.get(0);
	}
	@Override
	public Map<String, Object> getCourseRes(String id) {
		String sql = "select source_name,attId from %s where id = '%s' and valid = 1";
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try {
			list = jdbctemplate.queryForList(String.format(sql, "education.v_courseres_file",id));
		} catch (Exception e) {
			list.get(0).put("error", "error");
		}
		return list.get(0);
	}

	@Override
	public boolean addContent(Map<String, Object> inputMap, String operator) {
		boolean isSuccess = commonDataService.add(operator, "education.course_list", inputMap);
		return isSuccess;
	}

	@SuppressWarnings("null")
	@Override
	public DataVector<Map<String, Object>> getList(String type,int state,String user,RequestInput requestInput) {
		StringBuffer whereStr = new StringBuffer();
		if(type.equals("2")){
			 whereStr.append("creater").append("=").append("'").append(user).append("'");
		}
		if(type.equals("")){
			
		}
		if(whereStr.length() > 0){
			whereStr.append(" and ");
		}
		if(state == -1){
			
		}else {
			whereStr.append("state=").append("'").append(state).append("'");
		}
		String sortStr = " createTime desc";
		DataVector<Map<String, Object>> listData = commonDataService.getListData("education.v_course_class_list", whereStr.toString(), sortStr, requestInput);
		return listData;
	}
	
	@Override
	public boolean update(String id, Map<String, Object> inputMap, String operater) {
		
		Map<String, Object> updateMap = new HashMap<String,Object>();
		
		String pdfPptRel = inputMap.get("TimeArrAy").toString();
		pdfPptRel = pdfPptRel.substring(1, pdfPptRel.length()-1);
		pdfPptRel = pdfPptRel.replace(", ",",");
		
		String contentPptRel = "";
		String contentStr = "";
		@SuppressWarnings("unchecked")
		List<Object> contentlist = (List<Object>) inputMap.get("OutlineContent");
		if ( contentlist!=null && contentlist.size()>0 ) {
			for (Object object1 : contentlist) {
				List<String> content= (List<String>)object1;
				if (content!=null) {
					contentPptRel += content.get(0)+",";
					contentStr += content.get(1)+"&";
				}
			}
		}
				
		inputMap.remove("TimeArrAy");		
		inputMap.remove("OutlineContent");		
		updateMap.putAll(inputMap);
		updateMap.put("pdfPptRel", pdfPptRel);
		updateMap.put("contentStr", contentStr);
		updateMap.put("contentPptRel", contentPptRel);
		
		boolean isSuccess = commonDataService.update( operater, tableName,"id", id, updateMap);
		return isSuccess;
	}
	
	@Override
	public List<Map<String, Object>> getSourseList(String courseId, String pid, String type,String classType) {
		String sql = "";
		switch (type) {
		case "child":
			sql = "Select * from education.v_course where courseId= '"+courseId+"' and id = '"+pid+"' and valid=1";
			break;
		case "parent":
			sql = "Select * from education.v_course where courseId= '"+courseId+"' and pid = '"+pid+"' and valid=1";
			break;
		case "all":
			sql = "Select * from education.v_course where courseId= '"+courseId+"' and valid=1";
			break;
		case "picture":
			switch (classType) {
			case "child":
				sql = "Select * from education.v_course_picture where courseId= '"+courseId+"' and id = '"+pid+"' and valid=1";
				break;
			case "parent":
				sql = "Select * from education.v_course_picture where courseId= '"+courseId+"' and pid = '"+pid+"' and valid=1";
				break;
			case "all":
				sql = "Select * from education.v_course_picture where courseId= '"+courseId+"' and valid=1";
				break;
			default:
				break;
			}
			break;

		default:
			break;
		}
		List<Map<String, Object>> reList = new ArrayList<Map<String,Object>>();
		try {
			reList = jdbctemplate.queryForList(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return reList;
	}
	
	@Override
	public boolean delete(String id) {
		String sql = "DELETE education.course,education.course_list FROM education.course"
				+ " LEFT JOIN education.course_list ON education.course.id=education.course_list.courseId WHERE education.course.id='"+id+"'";
		boolean isSuccess = true;
		try {
			int delete = jdbctemplate.update(sql);
			if(delete<0){
				isSuccess = false;
			}
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> add(Map<String, Object> inputMap, String operator) {
		Map<String, Object> inputParamMap = new HashMap<String, Object>();
		String pdfPptRel = inputMap.get("TimeArrAy").toString();
		pdfPptRel = pdfPptRel.substring(1, pdfPptRel.length()-1);
		pdfPptRel = pdfPptRel.replace(", ",",");
		
		String contentPptRel = "";
		String contentStr = "";
		List<Object> contentlist = (List<Object>) inputMap.get("OutlineContent");
		if ( contentlist!=null && contentlist.size()>0 ) {
			for (Object object1 : contentlist) {
				List<String> content= (List<String>)object1;
				if (content!=null) {
					contentPptRel += content.get(0)+",";
					contentStr += content.get(1)+"&";
				}
			}
		}
		
		inputParamMap.put("class_name", inputMap.get("class_name"));//VARCHAR
		inputParamMap.put("class_source", inputMap.get("class_source"));//VARCHAR
		inputParamMap.put("class_ppt", inputMap.get("class_ppt"));//VARCHAR
		inputParamMap.put("class_con", inputMap.get("class_con"));//VARCHAR
		inputParamMap.put("class_id", inputMap.get("class_id"));//
		inputParamMap.put("type", inputMap.get("type"));//INT
		inputParamMap.put("creater", operator);
		inputParamMap.put("pdfPptRel", pdfPptRel);
		inputParamMap.put("contentStr", contentStr);
		inputParamMap.put("contentPptRel", contentPptRel);
		Map<String, Object> execute = new SimpleJdbcCall(jdbctemplate).withCatalogName("education")
				.withProcedureName("P_COURSE_ADD")
				.declareParameters(
						new SqlParameter("class_name",java.sql.Types.VARCHAR),
						new SqlParameter("class_source",java.sql.Types.VARCHAR),
						new SqlParameter("class_ppt",java.sql.Types.VARCHAR),
						new SqlParameter("class_con",java.sql.Types.VARCHAR),
						new SqlParameter("class_id",java.sql.Types.VARCHAR),
						new SqlParameter("type",java.sql.Types.INTEGER),
						new SqlParameter("creater",java.sql.Types.VARCHAR),
						new SqlParameter("pdfPptRel",java.sql.Types.VARCHAR),
						new SqlParameter("contentStr",java.sql.Types.VARCHAR),
						new SqlParameter("contentPptRel",java.sql.Types.VARCHAR),
						new SqlOutParameter("id",java.sql.Types.INTEGER)
						).execute(inputParamMap);
		return execute;	
	}

	@Override
	public boolean isRight(String id, String operator) {
		String sql = "select creater from "+tableName+" where id = '"+id+"' and valid = 1";
		String authorship = jdbctemplate.queryForObject(sql, String.class);
		if(operator.equals(authorship)){
			return true;
		}
		return false;
	}

	@Override
	public boolean updateState(String id, int state, String operator, Boolean isAudit) {
		boolean isSuccess = true;
		String sql = null;
		if (isAudit) {
			sql = "update %s set state=%s,auditor='%s',auditTime='%s' where id=%s";
		}else {
			sql = "update %s set state=%s,evaluator='%s',evalueTime='%s' where id=%s";
		}
		String dateStr = DateUtil.getDateStr(new Date(),DateType.YYYY_MM_DD_HH_mm_ss_SSS);
		try {
			int update = jdbctemplate.update(String.format(sql, tableName,state,operator,dateStr,id));
			if(update <= 0){
				isSuccess = false;
			}
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
	 /**
	 * 获取章节树数据
	 * @param courseId
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月3日
	 */
	@Override
	public List<Map<String, Object>> getTreeData(Integer courseId){
		String sql = "select * from education.course_list where valid=1 and courseId=%s";
		return jdbctemplate.queryForList(String.format(sql, courseId));
	}

	@Override
	public boolean updateContent(String id, Map<String, Object> inputMap, String operator) {
		boolean isSuccess = true;
		isSuccess = commonDataService.update(operator, "education.course_list", "id", id, inputMap);
		return isSuccess;
	}
	@Override
	public boolean updateSource(String id, Map<String, Object> inputMap, String operator) {
		boolean isSuccess = true;
		String sqlString = "update education.course_list set videoId = null where id='"+id+"'";
		try {
			int update = jdbctemplate.update(sqlString);
			if(update<1){
				isSuccess = false;
			}
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}

	@Override
	public boolean deleteDir(String id) {
		boolean isSuccess = true;
		isSuccess = commonDataService.delete("education.course_list", "id", id);
		return isSuccess;
	}

	@Override
	public List<Map<String, Object>> getTypeList() {
		List<Map<String, Object>> relList = new ArrayList<Map<String,Object>>();
		String sql = "select * from education.resource_class";
		try {
			relList = jdbctemplate.queryForList(sql);
		} catch (Exception e) {
			return new ArrayList<Map<String,Object>>();
		}
		return relList;
	}
	
	@Override
	public Integer toEstimate(String ids,String operator){
		StringBuffer idsBuffer = new StringBuffer();
		String[] split = ids.split(",");
		for(String id : split){
			Boolean estimateAssi = userAssignmentService.estimateAssi(Integer.parseInt(id), 1, 1);
			if (estimateAssi) {
				if (idsBuffer.length() > 0) {
					idsBuffer.append(",");
				}
				idsBuffer.append(id);
			}
		}
		if (idsBuffer.length() <= 0) {
			return 0;
		}
		String dateStr = DateUtil.getDateStr(new Date(),DateType.YYYY_MM_DD_HH_mm_ss_SSS);
		String sql = "update %s set state=1,mender='%s',updateTime='%s' where id in('%s')";
		return jdbctemplate.update(String.format(sql, tableName,operator,dateStr,idsBuffer.toString().replaceAll(",", "','")));
	}
	

}
